package com.hanbang.cxgz_2.view.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.media.AudioManager;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.hanbang.cxgz_2.R;
import com.hanbang.cxgz_2.utils.http.HttpLocalUtils;
import com.hanbang.cxgz_2.utils.other.LogUtils;
import com.hanbang.cxgz_2.utils.other.StringUtils;
import com.hanbang.videoplay.JCMediaManager;
import com.hanbang.videoplay.JCMediaPlayerListener;
import com.hanbang.videoplay.JCVideoPlayerManager;

import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_AUTO_COMPLETE;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_ERROR;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_NORMAL;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_PAUSE;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_PLAYING;
import static com.hanbang.videoplay.view.VideoPlayer.CURRENT_STATE_PREPAREING;

/**
 * 作者　　: 李坤
 * 创建时间:2016/9/14　14:52
 * 邮箱　　：496546144@qq.com
 * <p>
 * 功能介绍：
 */

public class TouTingMusicPlayView extends View implements JCMediaPlayerListener {

    public static int STATUS = CURRENT_STATE_NORMAL;

    /**
     * http://m2.music.126.net/feplW2VPVs9Y8lE_I08BQQ==/1386484166585821.mp3
     * <p>
     * * public static final int CURRENT_STATE_NORMAL = 0;
     * public static final int CURRENT_STATE_PREPAREING = 1;
     * public static final int CURRENT_STATE_PLAYING = 2;
     * public static final int CURRENT_STATE_PLAYING_BUFFERING_START = 3;
     * public static final int CURRENT_STATE_PAUSE = 5;
     * public static final int CURRENT_STATE_AUTO_COMPLETE = 6;
     * public static final int CURRENT_STATE_ERROR = 7;
     */
    private String url = "";
    private int state = CURRENT_STATE_NORMAL;
    private ValueAnimator voiceAnimator;
    private Paint paintBack = new Paint();
    private Paint paintText = new Paint();
    private Paint paintVoice = new Paint();
    private Path path = new Path();
    private float spaceSize = 0;//距离右边的间距
    private float circleRadius = 0;//头像的半径
    private float smallCircleRadius = 0;//上面小圆半径
    private float textSize = 0;//文字大小
    private float voiceCircleRadius = 0;//声音的小圆半径
    private float voiceSpaceSize = 0;//声音的间距
    private GestureDetectorCompat gesture;
    private String title = "1元偷听";
    private int voiceRank = 3;//声音的等级，播放的小喇叭
    private int voiceRankMax = 3;//声音的等级，播放的小喇叭
    private boolean isBuy = false;//是否购买
    private OnCallListener listener;

    public void setUrl(String url) {
        this.url = HttpLocalUtils.getHttpFileUrl(url);
    }

    /**
     * 回调
     *
     * @param listener
     */
    public void setOnCallListener(OnCallListener listener) {
        this.listener = listener;
    }


    public TouTingMusicPlayView(Context context) {
        this(context, null);
    }

    public TouTingMusicPlayView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TouTingMusicPlayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);

    }

    private void initView(Context context, AttributeSet attrs) {


        circleRadius = getResources().getDimensionPixelSize(R.dimen.dp_25);
        spaceSize = getResources().getDimensionPixelSize(R.dimen.dp_6);
        smallCircleRadius = getResources().getDimensionPixelSize(R.dimen.dp_10);
        voiceCircleRadius = getResources().getDimensionPixelSize(R.dimen.dp_5);
        voiceSpaceSize = getResources().getDimensionPixelSize(R.dimen.dp_6);
        textSize = getResources().getDimensionPixelSize(R.dimen.text_h);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TouTingMusicPlayView);
        circleRadius = typedArray.getDimension(R.styleable.TouTingMusicPlayView_TMPCircleRadius, circleRadius);
        spaceSize = typedArray.getDimension(R.styleable.TouTingMusicPlayView_TMPSpaceSize, spaceSize);
        smallCircleRadius = typedArray.getDimension(R.styleable.TouTingMusicPlayView_TMPSmallCircleRadius, smallCircleRadius);
        voiceCircleRadius = typedArray.getDimension(R.styleable.TouTingMusicPlayView_TMPVoiceCircleRadius, voiceCircleRadius);
        voiceSpaceSize = typedArray.getDimension(R.styleable.TouTingMusicPlayView_TMPVoiceSpaceSize, voiceSpaceSize);
        textSize = typedArray.getDimension(R.styleable.TouTingMusicPlayView_TMPTextSize, textSize);
        typedArray.recycle();

        setBackgroundResource(R.color.translucent);
        paintBack.setColor(getResources().getColor(R.color.green_touting));
        paintBack.setAntiAlias(true);//抗锯齿
        paintBack.setDither(true);//抗抖动
        paintBack.setStyle(Paint.Style.FILL);


        paintVoice.setColor(getResources().getColor(R.color.white));
        paintVoice.setAntiAlias(true);//抗锯齿
        paintVoice.setDither(true);//抗抖动
        paintVoice.setStyle(Paint.Style.STROKE);
        paintVoice.setStrokeWidth(getResources().getDimensionPixelSize(R.dimen.dp_2));


        paintText.setColor(getResources().getColor(R.color.white));
        paintText.setAntiAlias(true);//抗锯齿
        paintText.setDither(true);//抗抖动
        paintText.setStyle(Paint.Style.FILL);
        paintText.setTextAlign(Paint.Align.LEFT);
        paintText.setTextSize(textSize);


        if (!isInEditMode()) {
//            ViewUtils.inject(this, v);


        }
        gesture = new GestureDetectorCompat(context, onGestureListener);


        voiceAnimator = ValueAnimator.ofInt(1, voiceRankMax + 1);
        voiceAnimator.setDuration((voiceRankMax) * 1000);
        voiceAnimator.setRepeatCount(ValueAnimator.INFINITE);
        voiceAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                voiceRank = 1;
                setTitle("点击暂停");
                invalidate();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                voiceRank = voiceRankMax;
                setTitle("点击播放");
                paintBack.setShader(null);
                invalidate();
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                voiceRank = voiceRankMax;
                paintBack.setShader(null);
                invalidate();
            }
        });

        voiceAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            boolean isTep = false;//是否是多次达到某个值

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int v = (int) animation.getAnimatedValue();
                if (v == voiceRank && isTep) {
                    return;
                }
                if (v > voiceRank) {
                    isTep = true;
                }

                if (isTep && v >= voiceRank || (voiceRank >= voiceRankMax && v == 1)) {
                    isTep = true;
                    voiceRank = v;
                    if (voiceRank > voiceRankMax) {
                        voiceRank = 1;
                    }
                    setBackShader();
                    invalidate();
                }
            }
        });
    }

    private void setBackShader() {
        if (state == CURRENT_STATE_PLAYING) {
            int allTime = JCMediaManager.instance().mediaPlayer.getDuration();//ms
            int curr = JCMediaManager.instance().getCurrentPosition();
            float p = curr / (allTime * 1.0f);

            LogUtils.e(url + "   " + p + "    " + allTime + "   " + curr);
            int[] color = new int[]{getResources().getColor(R.color.red_tou_ting), getResources().getColor(R.color.main_color),
                    getResources().getColor(R.color.red_tou_ting)};
            float start = p - 0.1f;
            if (start < 0) {
                start = 0;
            }
            float end = p + 0.1f;
            if (end > 1) {
                end = 1;
            }
            float[] position = new float[]{start, p, end};

            LinearGradient mShader = new LinearGradient(0 - spaceSize / 2.5f, getHeight() / 2.0f, getWidth(), getHeight() / 2.0f,
                    color, position, Shader.TileMode.CLAMP);
//            Matrix matrix = new Matrix();
//            matrix.setTranslate(mDx,0);
//            mShader.setLocalMatrix(matrix);
            paintBack.setShader(mShader);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        ViewGroup.LayoutParams pa = getLayoutParams();
        if (pa instanceof LinearLayout.LayoutParams) {
            ((LinearLayout.LayoutParams) pa).leftMargin = -(int) (circleRadius);
        } else if (pa instanceof FrameLayout.LayoutParams) {
            ((FrameLayout.LayoutParams) pa).leftMargin = (int) (circleRadius);
        } else if (pa instanceof RelativeLayout.LayoutParams) {
            ((RelativeLayout.LayoutParams) pa).leftMargin = (int) (circleRadius);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBack(canvas);
        drawText(canvas);
        drawVoice(canvas);
    }

    private void drawBack(Canvas canvas) {
        path.reset();
        path.moveTo(spaceSize / 2.5f, getHeight());//移动点到左下角
        path.quadTo(circleRadius * 1.2f, getHeight(), circleRadius + spaceSize, smallCircleRadius);//画二阶贝塞尔曲线
        //  path.lineTo(circleRadius +spaceSize, smallCircleRadius);
        path.quadTo(circleRadius + spaceSize, 0, circleRadius + spaceSize + smallCircleRadius, 0);
        //  path.cubicTo(circleRadius, getHeight(),circleRadius, 0,90,0);//三阶贝塞尔曲线
        path.lineTo(getWidth() - smallCircleRadius, 0);
        path.quadTo(getWidth(), 0, getWidth(), smallCircleRadius);

        path.lineTo(getWidth(), getHeight() - smallCircleRadius);
        path.quadTo(getWidth(), getHeight(), getWidth() - smallCircleRadius, getHeight());
        path.lineTo(0, getHeight());
        canvas.drawPath(path, paintBack);
    }

    private void drawText(Canvas canvas) {
        Paint.FontMetricsInt fontMetrics = paintText.getFontMetricsInt();//文字的4根线，baseLine为0，top为负值， bottom为正数
        int baseline = (getHeight() - fontMetrics.top - fontMetrics.bottom) / 2;
        canvas.drawText(title, circleRadius + smallCircleRadius + spaceSize + voiceCircleRadius + voiceSpaceSize * 5, baseline, paintText);
    }

    private void drawVoice(Canvas canvas) {

        float circleX = circleRadius + smallCircleRadius + spaceSize + voiceCircleRadius;
        float circleY = getHeight() / 2.0f;
        canvas.drawCircle(circleX, circleY, voiceCircleRadius, paintVoice);
        for (int i = 0; i < voiceRank; i++) {
            float voiceSpaceSizeTemp = voiceSpaceSize * (i + 1);
            RectF rect = new RectF(circleX - voiceCircleRadius - voiceSpaceSizeTemp, circleY - voiceCircleRadius - voiceSpaceSizeTemp,
                    circleX + voiceCircleRadius + voiceSpaceSizeTemp, circleY + voiceCircleRadius + voiceSpaceSizeTemp);
            canvas.drawArc(rect, -30, 60, false, paintVoice
            );
        }

    }

    public void setBuyEnable(boolean e) {
        if (state == CURRENT_STATE_PLAYING || state == CURRENT_STATE_PAUSE) {
            STATUS = state;
        }
        LogUtils.e("" + JCMediaManager.instance().url);
        if (StringUtils.isEquals(JCMediaManager.instance().url, url)) {
            state = STATUS;
            if (state == CURRENT_STATE_PLAYING) {
                startVoice();
            } else if (state == CURRENT_STATE_PAUSE) {
                setTitle("点击播放");
            }
            return;
        }
        if (e) {
            setTitle("点击播放");
            paintBack.setColor(getResources().getColor(R.color.red_tou_ting));
        } else {
            setTitle("1元偷听");
            paintBack.setColor(getResources().getColor(R.color.green_touting));
        }

        voiceAnimator.cancel();
        invalidate();
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        RectF rect = new RectF(circleRadius + smallCircleRadius + spaceSize
                , 0f, getWidth(), getHeight());
        if (rect.contains(x, y)) {
            return gesture.onTouchEvent(event);
        } else {
            return super.onTouchEvent(event);
        }


    }


    GestureDetector.SimpleOnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (isBuy) {

                if (state == CURRENT_STATE_NORMAL || state == CURRENT_STATE_ERROR || state == CURRENT_STATE_AUTO_COMPLETE) {
                    prepare();
                } else if (state == CURRENT_STATE_PLAYING) {
                    pause();
                } else if (state == CURRENT_STATE_PAUSE) {
                    play();
                }
            } else if (listener != null) {
                listener.onBuy(isBuy);
            }
            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    };

    public void setBuy(boolean buy) {
        isBuy = buy;
        setBuyEnable(buy);
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void startVoice() {

        if (voiceAnimator.isStarted()) {
            voiceAnimator.cancel();
        }
        voiceAnimator.start();
    }

    public void prepare() {
        if (TextUtils.isEmpty(url)) return;
        if (state != CURRENT_STATE_PREPAREING) {
            JCMediaManager.instance().releaseMediaPlayer();
            if (JCVideoPlayerManager.listener() != null) {
                JCVideoPlayerManager.listener().onCompletion();
            }
            JCVideoPlayerManager.setListener(this);
            JCMediaManager.instance().prepare(url, null, false);
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
            state = CURRENT_STATE_PREPAREING;
            setTitle("加载中");
            invalidate();
        }
    }

    /**
     * 播放音乐
     */
    private void play() {
        if (state == CURRENT_STATE_PAUSE || state == CURRENT_STATE_PREPAREING) {
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            JCMediaManager.instance().mediaPlayer.start();//播放
            state = CURRENT_STATE_PLAYING;
            setTitle("点击暂停");
            startVoice();
            invalidate();
        }
    }


    /**
     * 暂停音乐
     */
    public void pause() {

        if (state == CURRENT_STATE_PLAYING && JCMediaManager.instance().mediaPlayer.isPlaying()) {
            JCMediaManager.instance().mediaPlayer.pause();
            state = CURRENT_STATE_PAUSE;
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
            setTitle("点击播放");
            voiceAnimator.cancel();
            invalidate();
        }
    }

    /**
     * 作者　　: 李坤
     * 创建时间: 2016/9/3 15:30
     * <p>
     * 方法功能：
     */

    public void stop() {
        if (state != CURRENT_STATE_NORMAL) {
            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
            JCMediaManager.instance().mediaPlayer.stop();
            setTitle("点击播放");
            voiceAnimator.cancel();
            invalidate();
        }
    }

    public AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            //AUDIOFOCUS_GAIN, AUDIOFOCUS_LOSS, AUDIOFOCUS_LOSS_TRANSIENT and AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK.
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN://用于指示音频焦点的增益，或音频设备的请求，持续时间未知。
                    play();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS://用来表示持续时间未知的音频焦点损失。
                    stop();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://用于指示音频重点短暂丧失。
                    pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    //用于指示音频重点短暂丧失在音频焦点，如果它想继续打球可以降低其输出音量的失败者（也被称为“回避”），作为新的焦点所有者不需要别人沉默。
                    break;
            }
        }
    };

    /**
     * 释放资源, 外部调用
     */
    public static void release() {
        try {
            if (JCMediaManager.instance().mediaPlayer != null) {
                if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                    JCMediaManager.instance().mediaPlayer.stop();
                }
                if (JCMediaManager.instance().mediaPlayer != null) {
                    JCMediaManager.instance().mediaPlayer.release();
                }
            }
            if (JCVideoPlayerManager.listener() != null) {
                JCVideoPlayerManager.listener().onCompletion();
                JCVideoPlayerManager.setListener((JCMediaPlayerListener) null);
            }
            if (JCVideoPlayerManager.lastListener() != null) {
                JCVideoPlayerManager.lastListener().onCompletion();
                JCVideoPlayerManager.setLastListener((JCMediaPlayerListener) null);
            }
            JCMediaManager.instance().releaseMediaPlayer();
        } catch (Exception e) {

        }
    }


    @Override
    public void onPrepared() {
        if (state == CURRENT_STATE_PREPAREING) {
            play();
        }
    }

    @Override
    public void onCompletion() {
        state = CURRENT_STATE_AUTO_COMPLETE;
        JCVideoPlayerManager.setListener((JCMediaPlayerListener) null);
        setTitle("点击播放");
        voiceAnimator.cancel();
        invalidate();
    }

    @Override
    public void onAutoCompletion() {
        state = CURRENT_STATE_AUTO_COMPLETE;
        if (JCVideoPlayerManager.listener() != null) {
            JCVideoPlayerManager.listener().onCompletion();
            JCVideoPlayerManager.setListener((JCMediaPlayerListener) null);
        }
        if (JCVideoPlayerManager.lastListener() != null) {
            JCVideoPlayerManager.lastListener().onCompletion();
            JCVideoPlayerManager.setLastListener((JCMediaPlayerListener) null);
        }
        setTitle("点击播放");
        voiceAnimator.cancel();

    }

    @Override
    public void onBufferingUpdate(int i) {

    }

    @Override
    public void onSeekComplete() {

    }

    @Override
    public void onError(int i, int i1) {
        state = CURRENT_STATE_ERROR;
        setTitle("出错啦");
        voiceAnimator.cancel();
    }

    @Override
    public void onRelease() {

//        setTitle("点击播放");
//        voiceAnimator.cancel();
//        state = CURRENT_STATE_NORMAL;
//        invalidate();


    }

    @Override
    public void onInfo(int i, int i1) {

    }

    @Override
    public void onVideoSizeChanged() {

    }

    @Override
    public void goBackThisListener() {

    }

    @Override
    public boolean goToOtherListener() {
        return false;
    }

    @Override
    public void autoFullscreenLeft() {

    }

    @Override
    public void autoFullscreenRight() {

    }

    @Override
    public void autoQuitFullscreen() {

    }


    public interface OnCallListener {
        void onBuy(boolean isBuy);
    }
}
